import JSONAPISerializer from "json-api-serializer"
import request from "../../utils/request";
import flarum from "../../flarum";
import {urlEncode} from "../../utils/tools";
import {formatOptions} from "../../utils/util";

export class Discussions {
    constructor() {
        const that = this
        that.serializer = new JSONAPISerializer()
        that.serializer.register("discussions", {
            id: "id",
            relationships: {
                users: {
                    type: "users"
                },
                tags: {
                    type: "tags"
                },
                posts: {
                    type: "posts"
                },
                discussions: {
                    type: "discussions"
                }
            },
            topLevelMeta: function(data, extraData) {
                return {
                    count: extraData.count,
                    total: data.length
                };
            }
        })

        that.serializer.register('users', {
            type: "users",
            id: "id"
        })

        that.serializer.register('tags', {
            type: "tags",
            id: "id"
        })

        that.serializer.register('posts', {
            type: "posts",
            id: "id"
        })

        that.serializer.register('discussions', {
            type: "discussions",
            id: "id"
        })
    }

    /**
     * 获取API地址
     * @param sort
     * @param offset
     * @param tag
     * @param author
     * @param query
     * @param include
     * @returns {string}
     */
    getApi(sort = "",
           offset = 0,
           tag = "",
           author = "",
           query = "",
           include = "user,lastPostedUser,tags,tags.parent,firstPost") {
        let url = `${flarum.api}/discussions?include=${urlEncode(include)}&sort=${sort}&page[offset]=${offset}&page[limit]=20`
        if (tag) {
            url = `${url}&filter[tag]=${tag}`
        }
        if (author) {
            url = `${url}&filter[author]=${urlEncode(author)}`
        }

        if (query) {
            url = `${url}&filter[q]=${urlEncode(query)}`
        }

        return url
    }

    /**
     * 执行列表
     * @param params
     * @param func
     */
    execute(params = {}, func) {
        const that = this
        const url = that.getApi(params.sort, params.offset, params.tag, params.author, params.q)
        request.get(url).then(res => {
            that.data = res
            that.viewdata = that.serializer.deserialize("discussions", res)
            that.options = formatOptions(that.data)
            func(that.data, that.viewdata, that.options)
        }).catch(res => {})
    }
}